﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Windows;
using System.Windows.Markup;
using SilentWebsite.Web;

namespace SilentWebsite.ViewModels
{
    public static class DynamicControlFactory
    {
        private static Assembly lastAssembly;
        public static ICollection<DynamicControl> DynamicControls { get; set; }

        public static FrameworkElement Create(string name)
        {
            var template = DynamicControls.FirstOrDefault(x => x.Name.ToUpper() == name.ToUpper());
            if (template == null)
                return null;

            FrameworkElement element;

            if (string.IsNullOrWhiteSpace(template.Markup))
            {
                var type = GetType(template.ClrType);
                if (type == null)
                    return null;

                element = Activator.CreateInstance(type) as FrameworkElement;
            }
            else
            {
                element = XamlReader.Load(template.Markup) as FrameworkElement;
            }

            return element;
        }
        public static Type GetType(string typeName)
        {
            var type = Type.GetType(typeName);
            if (type != null)
                return type;
            if (lastAssembly != null)
            {
                type = lastAssembly.GetType(typeName);
                if (type !=null)
                    return type;
            }
            foreach (var assembly in AppDomain.CurrentDomain.GetAssemblies())
            {
                type = assembly.GetType(typeName);
                if (type != null)
                {
                    lastAssembly = assembly;
                    return type;
                }
            }
            return null;
        }
    }
}